package org.goldfish.demo.apicall.analysis.code.upload.model;

import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.image.ImageView;
import lombok.Getter;
import org.springframework.stereotype.Component;

import java.awt.image.BufferedImage;
import java.io.IOException;

@Component
public class PdfImagePanelController {
    @FXML
    private Label fileNameLabel;
    @FXML
    private Label pageNumberLabel;
    @FXML
    private ImageView imageView;
    @FXML
    private TextArea replyArea;

    public void setPdfImageAnalysis(PdfImageAnalysis pdfImageAnalysis) throws IOException {
        fileNameLabel.setText(pdfImageAnalysis.getFile().getName());
        pageNumberLabel.setText("第 " + pdfImageAnalysis.getPageNumber() + " 页");
        
        // 将BufferedImage转换为JavaFX Image
        BufferedImage bufferedImage = pdfImageAnalysis.getImage();
        javafx.scene.image.Image fxImage = SwingFXUtils.toFXImage(bufferedImage, null);
        imageView.setImage(fxImage);
        
        // 监听分析结果更新
        Thread updateThread = new Thread(() -> {
            StringBuilder previousResponse = new StringBuilder();
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    Thread.sleep(1000); // 每秒检查一次更新
                    String currentResponse = pdfImageAnalysis.getResponse();
                    if (!currentResponse.equals(previousResponse.toString())) {
                        Platform.runLater(() -> 
                            replyArea.setText(currentResponse)
                        );
                        previousResponse.setLength(0);
                        previousResponse.append(currentResponse);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        });
        updateThread.setDaemon(true);
        updateThread.start();
    }
}